<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>SQL差异对比工具</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"/>
  <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.52.2/min/vs/loader.min.js"></script>--> 
  <script src="MonacoEditor/min/vs/loader.js"></script>
  <style>
    /* ===== 基础重置与字体 ===== */
    * { margin: 0; padding: 0; box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
    body { padding: 20px; height: 100vh; overflow: hidden; transition: background-color 0.3s, color 0.3s; }

    /* ===== 主题样式：浅色（默认）===== */
    body.theme-vs {
      background-color: #ffffff;
      color: #333333;
    }
    body.theme-vs input,
    body.theme-vs select,
    body.theme-vs button {
      background-color: #ffffff;
      color: #333333;
      border: 1px solid #cccccc;
    }

    /* ===== 主题样式：深色 ===== */
    body.theme-vs-dark {
      background-color: #1e1e1e;
      color: #cccccc;
    }
    body.theme-vs-dark input,
    body.theme-vs-dark select,
    body.theme-vs-dark button {
      background-color: #2d2d30;
      color: #cccccc;
      border: 1px solid #454545;
    }

    /* ===== 主题样式：高对比黑 ===== */
    body.theme-hc-black {
      background-color: #000000;
      color: #ffffff;
    }
    body.theme-hc-black input,
    body.theme-hc-black select,
    body.theme-hc-black button {
      background-color: #0c0c0c;
      color: #ffffff;
      border: 1px solid #ffffff;
    }

    /* ===== 页面布局 ===== */
    .container { display: flex; flex-direction: column; gap: 16px; height: 100%; }
    .header { display: flex; justify-content: space-between; align-items: center; }
    .title { font-size: 20px; font-weight: 600; }
    .controls { display: flex; gap: 12px; }
    select, button { padding: 6px 12px; border-radius: 6px; font-size: 14px; }
    button { cursor: pointer; }
    button:disabled { background: #cccccc; cursor: not-allowed; }
    button:not(:disabled) { transition: background-color 0.2s; }

    /* 默认按钮样式根据主题自动适配（由上面 body.theme-* input/button 控制） */
    button {
      background: var(--btn-bg, #0066cc);
      color: var(--btn-text, white);
      border: none;
    }
    button:hover:not(:disabled) {
      background: var(--btn-hover, #0052a3);
    }

    /* 编辑器容器布局 */
    .editors-container { display: flex; gap: 16px; height: 45%; }
    .editor-wrapper { flex: 1; border: 1px solid #ccc; border-radius: 8px; overflow: hidden; }
    .diff-viewer { 
      display: none; 
      height: 45%; 
      border: 1px solid #ccc; 
      border-radius: 8px; 
    }

    @media (max-width: 768px) {
      .editors-container { flex-direction: column; height: 60%; }
      .diff-viewer { height: 30%; }
    }

    /* 加载提示 */
    #loadingTip {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 20px 30px;
      border-radius: 8px;
      font-size: 16px;
      z-index: 9999;
      display: block;
    }
    #loadingTip i {
      margin-right: 8px;
      animation: spin 1s linear infinite;
    }
    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
  </style>
</head>
<body class="theme-vs">
  <div id="loadingTip">
    <i class="fas fa-spinner"></i> 正在加载 SQL 对比模块，请稍候...
  </div> 

  <div class="container">
    <div class="header">
      <div class="title">SQL差异对比工具</div>
      <div class="controls">
        <select id="themeSelector">
          <option value="vs">浅色主题</option>
          <option value="vs-dark">深色主题</option>
          <option value="hc-black">高对比度黑</option>
        </select>
        <button id="compareBtn" disabled>显示差异</button>	 
      </div>
    </div>

    <div class="editors-container">
      <div class="editor-wrapper" id="leftEditor"></div>
      <div class="editor-wrapper" id="rightEditor"></div>
    </div>

    <div class="diff-viewer" id="diffViewer"></div>
  </div>
   <script>
        // 封装函数：获取当前网页的网络目录路径（不包含最后的HTML文件名）
        function getCurrentNetworkDirectoryPath() {
            var pathname = window.location.pathname;
            var lastSlashIndex = pathname.lastIndexOf('/');

            var directoryPath;
            if (lastSlashIndex > 0) {
                directoryPath = pathname.substring(0, lastSlashIndex + 1); // 保留最后的斜杠
            } else {
                directoryPath = '/'; // 根目录情况
            }

            var baseUrl = window.location.protocol + '//' + window.location.host + directoryPath;
            return baseUrl;
        }

                
  </script>
  <script>
    let leftEditor, rightEditor, diffEditor;

    // 更新页面主题（包括编辑器和页面 UI）	
    function updatePageTheme(theme) {
      document.body.className = '';
      document.body.classList.add(`theme-${theme}`);
      if (leftEditor) monaco.editor.setTheme(theme);
      if (rightEditor) monaco.editor.setTheme(theme);
      if (diffEditor) diffEditor.updateOptions({ theme });
    }

    // 加载 Monaco 编辑器
    //require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.52.2/min/vs' }}); 
    //src="MonacoEditor/min/vs/loader.js";
	var vs_path = getCurrentNetworkDirectoryPath()+"MonacoEditor/min/vs";
	// 示例：在控制台输出结果
    console.log("当前网络目录路径（不包含HTML文件）是：" + vs_path);
	
	require.config({ paths: { vs:  vs_path }});
    require(['vs/editor/editor.main'], function () {
      console.log('✅ Monaco 编辑器核心模块加载完成');

      const defaultTheme = 'vs';
      updatePageTheme(defaultTheme);
      monaco.editor.setTheme(defaultTheme);

      // 创建左侧编辑器
      leftEditor = monaco.editor.create(document.getElementById('leftEditor'), {
        value: '', language: 'sql', theme: defaultTheme, automaticLayout: true,
        minimap: { enabled: false }, scrollBeyondLastLine: false	
      });
		console.log('✅ Monaco 编辑器初始化绑定（左边）');
		
      // 创建右侧编辑器
      rightEditor = monaco.editor.create(document.getElementById('rightEditor'), {
        value: '', language: 'sql', theme: defaultTheme, automaticLayout: true,
        minimap: { enabled: false }, scrollBeyondLastLine: false
      });
		console.log('✅ Monaco 编辑器初始化绑定（右边）');
		
      // 启用对比按钮
      document.getElementById('compareBtn').disabled = false;

      // 隐藏加载提示
      const loadingTip = document.getElementById('loadingTip');
      if (loadingTip) loadingTip.style.display = 'none';

      // 主题切换事件
      document.getElementById('themeSelector').addEventListener('change', function () {
        const theme = this.value;
        updatePageTheme(theme);
      });

      // ===== 全局函数：供外部（如活字格）调用 =====
      window.setLeftSql = function (sql) {
        if (leftEditor) {
          leftEditor.setValue(sql);
          console.log('✅ 已设置左侧 SQL');
          return true;
        }
        console.error('❌ setLeftSql: leftEditor 未初始化');
        return false;
      };


      window.setRightSql = function (sql) {
        if (rightEditor) {
          rightEditor.setValue(sql);
          console.log('✅ 已设置右侧 SQL');
          return true;
        }
        console.error('❌ setRightSql: rightEditor 未初始化');
        return false;
      };
      
	  //默认值防止diff报错
	  window.setLeftSql('左代码样例：select 1');
      window.setRightSql('右代码样例：select 2');
	  
      window.showDiff = function () {
        const original = leftEditor ? leftEditor.getValue() : '';
        const modified = rightEditor ? rightEditor.getValue() : '';
        if (!original && !modified) {
          console.error('❌ 请输入至少一段SQL脚本');
		  //alert('请输入至少一段SQL脚本');
          return;
        }

        const diffViewer = document.getElementById('diffViewer');
        diffViewer.style.display = 'block';

        if (diffEditor) diffEditor.dispose();

        diffEditor = monaco.editor.createDiffEditor(diffViewer, {
          enableSplitViewResizing: true, renderIndicators: true,
          theme: document.getElementById('themeSelector').value
        });

        const originalModel = monaco.editor.createModel(original, 'sql');
        const modifiedModel = monaco.editor.createModel(modified, 'sql');
        diffEditor.setModel({ original: originalModel, modified: modifiedModel });
		console.log('✅ 对比成功！');
      };

      // 绑定按钮事件
      document.getElementById('compareBtn').addEventListener('click', showDiff);

      /*
      // ===== 活字格集成：自动加载 SQL 并初始化 =====
      function initForguncyIntegration() {
        try {
          if (window.parent && window.parent.Forguncy) {
            console.log('🔌 检测到活字格环境，开始获取 SQL');
            const Forguncy = window.parent.Forguncy;
            const sqlLeft = Forguncy.Page.getCell("script_left").getValue();
            const sqlRight = Forguncy.Page.getCell("script_right").getValue();

            console.log('📥 获取到左侧SQL长度:', sqlLeft?.length, '右侧SQL长度:', sqlRight?.length);

            if (typeof window.setLeftSql === 'function' && typeof window.setRightSql === 'function') {
              window.setLeftSql(sqlLeft || '');
              window.setRightSql(sqlRight || '');
			  
              window.showDiff();
              // 通知活字格 SQL 设置成功
              if (window.parent && window.parent.postMessage) {
                window.parent.postMessage({
                  type: 'SQL_SET_SUCCESS',
                  timestamp: Date.now()
                }, '*');
              }
            } else {
              console.error('❌ setLeftSql / setRightSql 函数不可用');
            }
          }
        } catch (error) {
          console.error('❌ 活字格集成出错:', error);
        }
      }

      // 通知活字格：编辑器已就绪
      if (window.parent && window.parent.postMessage) {
        window.parent.postMessage({
          type: 'SQL_EDITOR_READY',
          message: 'SQL编辑器已初始化完成，可安全调用 setLeftSql / setRightSql 或 showDiff',
          timestamp: Date.now()
        }, '*');
      }

      // 执行活字格自动加载逻辑
      initForguncyIntegration();
	  
	  */
	 /* // 1秒后执行initForguncyIntegration函数
      setTimeout(function() {
        console.log('🔄 1秒后再次执行 initForguncyIntegration()');
        initForguncyIntegration();
      }, 1000);
	  */
	 
    });
  </script>
</body>
</html>
